package com.hmall.gateway.filter;


import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("请求路径：{}", path);
//        List<String> excludePaths = authProperties.getExcludePaths();
        // 检查是否匹配任意放行路径
        for (String excludePath : authProperties.getExcludePaths()) {
            if (pathMatcher.match(excludePath, path)) {
                log.info("路径 {} 被放行", path);
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("Authorization");
        if (StrUtil.isNotEmpty(token)) {
            try {
                Long userId = jwtTool.parseToken(token);
                request.mutate().header("user-info", String.valueOf(userId));
                return chain.filter(exchange);
            } catch (Exception e) {
                log.error("解析token失败", e);
            }
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
